package com.java2007.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 解决中文乱码过滤器
 * @author ZOU
 */
@WebFilter("/*")
public class CharsetEncodingFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;



        //放行文件
        String uri =request.getRequestURI();
        System.out.println(uri);
        //节约查询资源，放行静态资源
        if (uri == null || uri.endsWith(".html") || uri.endsWith(".jsp")|| uri.endsWith(".css") || uri.endsWith(".js")|| uri.endsWith(".png")){
            chain.doFilter(request,response);
            System.out.println("放行---->"+uri);
            return;
        }
        //处理请求中文乱码：
        request.setCharacterEncoding("UTF-8");
        //设置浏览器端解码：
        response.setContentType("text/html;charset=UTF-8");

        chain.doFilter(request,response);

    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
